package com.ysxsoft.wdg.adapter.order;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.ysxsoft.wdg.MyApplication;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.AddressBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.cart.ShopcartBean;
import com.ysxsoft.wdg.bean.response.CollectShopResponse;
import com.ysxsoft.wdg.bean.response.ShouResponse;
import com.ysxsoft.wdg.bean.response.StPayResponse;
import com.ysxsoft.wdg.bean.response.WxResponse;
import com.ysxsoft.wdg.bean.zy.ZyOrderDetailBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.pay.PayListenerUtils;
import com.ysxsoft.wdg.pay.PayPopWindow2;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.center_zy.GoodsDetailActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.ZyGoodsConfirmActivity;
import com.ysxsoft.wdg.ui.activity.order.AplyBackOrderActivity;
import com.ysxsoft.wdg.ui.activity.order.EmsActivity;
import com.ysxsoft.wdg.ui.activity.order.ZyOrderPlActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ListObserverMap;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class ZyOrderDetailActivity extends BaseActivity implements PayResultListener {

    private boolean isZy = true;//是自营订单

    public static void start(Context context, String orderid, boolean isZy) {
        Intent intent = new Intent(context, ZyOrderDetailActivity.class);
        intent.putExtra("orderid", orderid);
        intent.putExtra("isZy", isZy);
        context.startActivity(intent);
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address_address)
    TextView tvAddressAddress;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_goods_money)
    TextView tvGoodsMoney;
    @BindView(R.id.tv_yun)
    TextView tvYun;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.parent)
    RelativeLayout parent;
    @BindView(R.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;
    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R.id.tv_l)
    TextView tv_l;@BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.tv_r)
    TextView tv_r;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private String phone = "", orderid = "", uid = "";
    private ZyOrderDetailAdapter adapter;
    private String mobile = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zy_order_detail;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("订单详情");

        uid = SharePrefUtils.getUserId();
        orderid = getIntent().getStringExtra("orderid");
        isZy = getIntent().getBooleanExtra("isZy", true);

        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        adapter = new ZyOrderDetailAdapter(R.layout.include_order_goods);
        recyclerview.setAdapter(adapter);

        PayListenerUtils.getInstance(this).addListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        getDetail();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PayListenerUtils.getInstance(this).removeListener(this);
    }

    private void getDetail() {
        multStatusView.showLoading();
        mApiHelper.getZyOrderDetail(uid, orderid, new Observer<BaseBean<ZyOrderDetailBean>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<ZyOrderDetailBean> baseBean) {
                multStatusView.showContent();
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    ZyOrderDetailBean data = baseBean.getData();
                    fillView(data);
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                multStatusView.showError();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 填充视图
     *
     * @param bean
     */
    private void fillView(ZyOrderDetailBean bean) {

        ZyOrderDetailBean.OrderBean orderBean = bean.getOrder();
        //1.订单状态
        tvStatus.setText(orderBean.getStatus());
        if (orderBean.getO_status() > 0) {//不是未付款状态
            //隐藏倒计时
        } else {
            //显示倒计时
        }

        //2.收货人地址
        AddressBean addressBean = bean.getAddress();
        if (addressBean != null) {
            tvAddressName.setText(addressBean.getName());
            tvAddressPhone.setText(addressBean.getPhone());
            tvAddressAddress.setText(addressBean.getCity() + addressBean.getProvince() + addressBean.getCounty() + addressBean.getAddress());
        }
        mobile = bean.getMobile();
        //3.填充商品
        adapter.setNewData(bean.getDetail());//填充商品
        //4.商品金额
        tvGoodsMoney.setText("￥" + orderBean.getAccount());
        //5.运费
        tvYun.setText("￥" + bean.getYun());
        //6.订单总价
        tvTotalMoney.setText("￥" + orderBean.getAccount());
        //7.联系商家

        //8.订单详情
        tvOrderNo.setText("订单编号：" + orderBean.getDsn());
        tvOrderTime.setText("订单时间：" + orderBean.getAddtime());
        tvPayType.setText("支付方式：在线支付");
//        if(orderBean.getPaytype()==0){
//        }else if(orderBean.getPaytype()==1){
//            tvPayType.setText("支付方式：支付宝支付");
//        }else{
//            tvPayType.setText("支付方式：微信支付");
//        }
        if (orderBean.getO_status() > 0) {
            tvPayTime.setVisibility(View.VISIBLE);
            tvPayTime.setText("支付时间：" + orderBean.getPaytime());
        } else {
            tvPayTime.setVisibility(View.GONE);
        }

        //控制按钮
        switch (orderBean.getO_status()) {
            case 0://待付款
                tv_l.setText("取消订单");
                tv_r.setText("立即付款");
                tv_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelOrder(orderid);
                    }
                });
                tv_r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showPayWindow(orderBean.getAccount(), orderid);
                    }
                });
                break;
            case 1://待发货
                tv_l.setText("退款");
                tv_r.setText("提醒发货");
                tv_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AplyBackOrderActivity.start(ZyOrderDetailActivity.this, orderid, 1);//自营满减
                    }
                });
                tv_r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        notifyOrder(orderid);
                    }
                });
                break;
            case 2://待收货
                tv_l.setText("查看物流");
                tv_r.setText("确认收货");

                tv_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ZyOrderDetailActivity.this, EmsActivity.class);
                        intent.putExtra("emsNo", orderBean.getKd_no());
                        intent.putExtra("emsTypeCode", orderBean.getKd_type());
                        startActivity(intent);
                    }
                });

                tv_r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shou(orderid);
                    }
                });
                break;
            case 3://待评价
                tv_l.setText("查看物流");

                tv_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ZyOrderDetailActivity.this, EmsActivity.class);
                        intent.putExtra("emsNo", orderBean.getKd_no());
                        intent.putExtra("emsTypeCode", orderBean.getKd_type());
                        startActivity(intent);
                    }
                });
                if ("1".equals(orderBean.getDiscuss())) {//评论过就不显示已评价
                    tv_r.setText("已评价");
                    tvStatus.setText("已评价");
                } else {
                    tv_r.setText("立即评价");
                    tvStatus.setText("待评价");
                    tv_r.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (bean.getDetail() != null && bean.getDetail().size() > 0) {
                                ShopcartBean shopcartBean = bean.getDetail().get(0);
                                ZyOrderPlActivity.start(ZyOrderDetailActivity.this, shopcartBean.getDetailid() + "", orderBean.getOrderid(), 0,isZy);//评价自营商品
                            }
                        }
                    });
                }
                break;
            case 4://退款
                break;
            case 5:
                bottom.setVisibility(View.GONE);
                tvStatus.setText("退款中");
                break;
        }
    }

    @Override
    protected void setListener() {
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ShopcartBean item = (ShopcartBean) adapter.getItem(position);
                GoodsDetailActivity.start(mContext, item.getProductid());
            }
        });
    }

    @OnClick({R.id.title_finish, R.id.tv_kf})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.tv_kf:
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showToast("请稍后再试");
                    return;
                }
                ViewUtils.call(this, mobile);
//                AlertViewFactory.getInstance().getCallAlert(ZyOrderDetailActivity.this, mobile);
                break;
        }
    }

    PayPopWindow2 payPopWindow;

    private void showPayWindow(String payMoney, String orderId) {
        if (payPopWindow != null) {
            payPopWindow.dismiss();
            payPopWindow = null;
        }
        payPopWindow = new PayPopWindow2(this, payMoney);
        payPopWindow.show(parent);
        payPopWindow.setOnPayLiatener(new PayPopWindow2.OnPayLiatener() {
            @Override
            public void payType(int payType) {//payment= "3";//支付方式 1=>微信 2=>支付宝 3=>账户余额 4=>积分支付
                AlertUtils.payAlert(ZyOrderDetailActivity.this);
                switch (payType) {
                    case 0://余额支付
                        if (isZy) {
                            //自营支付
                            postPayYue(payMoney);
                        } else {
                            //满减支付//t 1支付宝2微信3余额支付
                            payByManJian("3",payMoney,orderid);
                        }
                        break;
                    case 1://支付宝支付
                        if (isZy) {
                            //自营支付
                            postPayZfb(payMoney);
                        } else {
                            //满减支付
                            payByManJian("1",payMoney,orderid);
                        }
                        break;
                    case 2://微信支付
                        if (isZy) {
                            //自营支付
                            postPayWx(orderid, payMoney);
                        } else {
                            //满减支付
                            payByManJian("2",payMoney,orderid);
                        }
                        break;
                }
            }
        });
    }

    /**
     * 取消订单
     */
    private void cancelOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.CANCEL_ORDER)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("type", "1")//1自营2实体
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
                        if(isZy){//自营订单取消订单成功
                            ListObserverMap.cancel("OrderZyFragment");
                        }else{//满减取消订单成功
                            ListObserverMap.cancel("OrderMjFragment");
                        }
                        finish();
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 通知发货
     */
    private void notifyOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.NOTIFY_SHOP)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 自营商城余额支付
     */
    private void postPayYue(String acount) {
        mApiHelper.payZyYue(SharePrefUtils.getUserId(), orderid, acount, "0", new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                AlertUtils.dismissAlert();
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    ToastUtils.showToast("支付成功!");
                    notifyPage();//支付通知
                    finish();
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void notifyPage(){
        if(isZy){//自营订单支付成功
            ListObserverMap.pay("OrderZyFragment");
        }else{//满减支付成功
            ListObserverMap.pay("OrderMjFragment");
        }
    }

    /**
     * 自营商城支付宝支付
     */
    private void postPayZfb(String payMoney) {
        mApiHelper.payZyZfb(SharePrefUtils.getUserId(), orderid, payMoney, "0", new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                AlertUtils.dismissAlert();
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayUtils.getInstance(mContext).pay(ZyOrderDetailActivity.this, PayUtils.PAY_TYPE_ALI, baseBean.getData(), null);
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 自营商城微信支付
     */
    private void postPayWx(String orderId, String payMoney) {
        mApiHelper.payZyWx(SharePrefUtils.getUserId(), orderId, payMoney, "0", new Observer<BaseBean<WxPayBean>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<WxPayBean> baseBean) {
                AlertUtils.dismissAlert();
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    PayUtils.getInstance(mContext).toWxPay(baseBean.getData());
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
                AlertUtils.dismissAlert();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 确认收货
     */
    private void shou(String orderId) {
        String type = isZy ? "1" : "2";
        OkHttpUtils.post()
                .url(UrlHost.SHOU)
                .addParams("type", type)//自营商城1满减2
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    ShouResponse shouResponse = JsonUtils.parseByGson(response, ShouResponse.class);
                    if (shouResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(shouResponse.getCode())) {
                        ToastUtils.showToast(shouResponse.getMs());
                        finish();
                    } else {
                        ToastUtils.showToast(shouResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    ///////////////////////////////////////////////////////////////////////////
    // 满减支付接口
    ///////////////////////////////////////////////////////////////////////////
    private void payByManJian(String t, String total, String orderid) {
        OkHttpUtils.post()
                .url(UrlHost.MAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("type", t)//1支付宝2微信3余额支付
                .addParams("total", total)
                .addParams("orderid", orderid)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        AlertUtils.dismissAlert();
                        if ("1".equals(t)) {//支付宝支付
                            postPayZfb(orderid, total);
                        } else if ("2".equals(t)) {//微信支付
                            postPayWx2(orderid, total);
                        } else if ("3".equals(t)) {//余额支付
                            notifyPage();
                            finish();
                        }
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 满减支付宝支付
     */
    private void postPayZfb(String orderId, String total) {
        OkHttpUtils.post()
                .url(UrlHost.TUAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .addParams("total", total)//总价格
                .addParams("type", "1")//1支付宝2微信3余额支付
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    StPayResponse stPayResponse = JsonUtils.parseByGson(response, StPayResponse.class);
                    if (stPayResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(stPayResponse.getCode())) {
                        PayUtils.getInstance(mContext).pay(ZyOrderDetailActivity.this, PayUtils.PAY_TYPE_ALI, stPayResponse.getData(), null);
                    } else {
                        ToastUtils.showToast(stPayResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 满减微信支付
     * @param orderId
     * @param total
     */
    private void postPayWx2(String orderId, String total) {
        OkHttpUtils.post()
                .url(UrlHost.TUAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .addParams("total", total)//总价格
                .addParams("type", "2")//1支付宝2微信3余额支付
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    WxResponse wxResponse = JsonUtils.parseByGson(response, WxResponse.class);
                    if (wxResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(wxResponse.getCode())) {
                        WxResponse.DataBean dataBean = wxResponse.getData();

                        WxPayBean bean = new WxPayBean();
                        bean.setAppid(dataBean.getAppid());
                        bean.setNoncestr(dataBean.getNoncestr());
                        bean.setPackageX(dataBean.getPackageX());
                        bean.setPartnerid(dataBean.getPartnerid());
                        bean.setPrepayid(dataBean.getPrepayid());
                        bean.setSign(dataBean.getSign());
                        bean.setTimestamp(""+dataBean.getTimestamp());
                        PayUtils.getInstance(mContext).toWxPay(bean);
                    } else {
                        ToastUtils.showToast(wxResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    @Override
    public void onPaySuccess() {
        ToastUtils.showToast("支付成功!");
        notifyPage();
        finish();
    }

    @Override
    public void onPayError() {
        ToastUtils.showToast("支付失败!");
    }

    @Override
    public void onPayCancel() {
        ToastUtils.showToast("支付取消!");
    }
}
